//
//  ViewController.m
//  DownloadManagerDemo
//
//  Created by ejiang on 2021/12/9.
//

#import "ViewController.h"
#import "DownloadManager.h"
#import "SectionHeader.h"
#import "DownloadListCell.h"

@interface ViewController ()<UITableViewDelegate, UITableViewDataSource, DownloadManagerDelegate, DownloadListCellAction>

@property (nonatomic, strong) NSArray * urlStrings;

@property (weak, nonatomic) IBOutlet SectionHeader *headerView;
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@end

@implementation ViewController

static NSString * const kMaxNumKey = @"MaxDownloadNum";

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    UIBarButtonItem * rightItem = [[UIBarButtonItem alloc] initWithTitle:@"添加" style:UIBarButtonItemStyleDone target:self action:@selector(handleClickRight)];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    [self.tableView registerNib:[UINib nibWithNibName:@"DownloadListCell" bundle:nil] forCellReuseIdentifier:@"DownloadListCell"];
    NSUInteger maxNum = [[NSUserDefaults standardUserDefaults] integerForKey:kMaxNumKey];
    if (maxNum == 0) {
        maxNum = 1;
        [[NSUserDefaults standardUserDefaults] setInteger:maxNum forKey:kMaxNumKey];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    
    
    [self.headerView.maxNumButton setTitle:[NSString stringWithFormat:@"最多同时下载 %d 个", (int)maxNum] forState:UIControlStateNormal];

    _headerView.titleLabel.text = [NSString stringWithFormat:@"下载任务：%d", (int)[DownloadManager sharedDownload].tasks.count];
    [_headerView configClickBlock:^(BOOL isSelected) {
        if (isSelected) {
            [[DownloadManager sharedDownload] pauseAll];
        } else {
            [[DownloadManager sharedDownload] resumeAll];
        }
    }];

    __weak typeof(self) weak_self = self;
    [_headerView configChangeMaxNumBlock:^{
        UIAlertController * alertC = [UIAlertController alertControllerWithTitle:@"最大同时下载数" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        for (int i = 0; i < 5; i++) {
            [alertC addAction:[UIAlertAction actionWithTitle:[NSString stringWithFormat:@"%d 个", (i + 1)] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [weak_self.headerView.maxNumButton setTitle:[NSString stringWithFormat:@"最多同时下载 %@", action.title] forState:UIControlStateNormal];
                NSUInteger number = [[action.title stringByReplacingOccurrencesOfString:@" 个" withString:@""] integerValue];
                [[NSUserDefaults standardUserDefaults] setInteger:number forKey:kMaxNumKey];
                [[NSUserDefaults standardUserDefaults] synchronize];
                [DownloadManager sharedDownload].maxDownloadNum = number;
            }]];
        }
        [alertC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
        [self presentViewController:alertC animated:YES completion:nil];
    }];
    
    
    [DownloadManager sharedDownload].maxDownloadNum = maxNum;
    [DownloadManager sharedDownload].delegate = self;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    [[DownloadManager sharedDownload] startAll];
}

- (void)handleClickRight {
    for (NSString * obj in self.urlStrings) {
        DownloadTask * task = [[DownloadTask alloc] initWithDownloadPath:obj targetName:nil targetDir:nil];
        task.extInfo = @{
            @"CurrentIndex" : @([self.urlStrings indexOfObject:obj]),
            @"TaskId" : task.taskId,
        };
        [[DownloadManager sharedDownload] addDownloadTask:task];
    }
    [self.tableView reloadData];
}

#pragma mark - DownloadManagerDelegate
- (void)downloadManagerDidChangeProgress:(DownloadTask *)task {
    dispatch_async(dispatch_get_main_queue(), ^{
        NSUInteger row = [[DownloadManager sharedDownload].tasks indexOfObject:task];
        NSIndexPath * indexPath = [NSIndexPath indexPathForRow:row inSection:0];
        [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    });
}

- (void)downloadManagerDidFinished:(DownloadTask *)task error:(NSError *)error {
    dispatch_async(dispatch_get_main_queue(), ^{
        NSUInteger row = [[DownloadManager sharedDownload].tasks indexOfObject:task];
        NSIndexPath * indexPath = [NSIndexPath indexPathForRow:row inSection:0];
        [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    });
}

- (void)downloadManagerDidPaused:(DownloadTask *)task {
    dispatch_async(dispatch_get_main_queue(), ^{
        NSUInteger row = [[DownloadManager sharedDownload].tasks indexOfObject:task];
        NSIndexPath * indexPath = [NSIndexPath indexPathForRow:row inSection:0];
        [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    });
}

- (void)downloadManagerDidResume:(DownloadTask *)task {
    dispatch_async(dispatch_get_main_queue(), ^{
        NSUInteger row = [[DownloadManager sharedDownload].tasks indexOfObject:task];
        NSIndexPath * indexPath = [NSIndexPath indexPathForRow:row inSection:0];
        [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    });
}

- (void)downloadManagerDidDeleteTask:(DownloadTask *)task {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.tableView reloadData];
    });
}

- (void)downloadManagerDidRetryTask:(DownloadTask *)task {
    dispatch_async(dispatch_get_main_queue(), ^{
        NSUInteger row = [[DownloadManager sharedDownload].tasks indexOfObject:task];
        NSIndexPath * indexPath = [NSIndexPath indexPathForRow:row inSection:0];
        [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    });
}

#pragma mark - DownloadListCellAction
- (void)downloadListCellDidClickDel:(DownloadListCell *)cell {
    NSIndexPath * indexPath = [self.tableView indexPathForCell:cell];
    DownloadTask * obj = [[DownloadManager sharedDownload].tasks objectAtIndex:indexPath.row];
    [[DownloadManager sharedDownload] deleteDownloadTask:obj.taskId];
}

- (void)downloadListCellDidClickRetry:(DownloadListCell *)cell {
    NSIndexPath * indexPath = [self.tableView indexPathForCell:cell];
    DownloadTask * obj = [[DownloadManager sharedDownload].tasks objectAtIndex:indexPath.row];
    if (obj.status != DownloadTaskStatusError) {
        return;
    }
    [[DownloadManager sharedDownload] retryDownloadTask:obj];
}

#pragma mark -
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [[DownloadManager sharedDownload].tasks count];
}

//- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
//    return 44;
//}

//- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
//    SectionHeader * header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"header"];
//    if (header == nil) {
//        header = [[SectionHeader alloc] initWithReuseIdentifier:@"header"];
//    }
//
//    NSUInteger maxNum = [[NSUserDefaults standardUserDefaults] integerForKey:kMaxNumKey];
//    [header.maxNumButton setTitle:[NSString stringWithFormat:@"最多同时下载 %d 个", (int)maxNum] forState:UIControlStateNormal];
//
//    header.titleLabel.text = [NSString stringWithFormat:@"下载任务：%d", (int)[DownloadManager sharedDownload].tasks.count];
//    [header configClickBlock:^(BOOL isSelected) {
//        if (isSelected) {
//            [[DownloadManager sharedDownload] pauseAll];
//        } else {
//            [[DownloadManager sharedDownload] resumeAll];
//        }
//    }];
//
//    __weak typeof(header) weak_header = header;
//    [header configChangeMaxNumBlock:^{
//            UIAlertController * alertC = [UIAlertController alertControllerWithTitle:@"最大同时下载数" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
//        for (int i = 0; i < 5; i++) {
//            [alertC addAction:[UIAlertAction actionWithTitle:[NSString stringWithFormat:@"%d 个", (i + 1)] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//                [weak_header.maxNumButton setTitle:[NSString stringWithFormat:@"最多同时下载 %@", action.title] forState:UIControlStateNormal];
//                NSUInteger maxNum = [[action.title stringByReplacingOccurrencesOfString:@" 个" withString:@""] integerValue];
//                [[NSUserDefaults standardUserDefaults] setInteger:maxNum forKey:kMaxNumKey];
//                [[NSUserDefaults standardUserDefaults] synchronize];
//                [DownloadManager sharedDownload].maxDownloadNum = maxNum;
//            }]];
//        }
//        [alertC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
//        [self presentViewController:alertC animated:YES completion:nil];
//    }];
//
//    return header;
//}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 110;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    DownloadListCell * cell = [tableView dequeueReusableCellWithIdentifier:@"DownloadListCell" forIndexPath:indexPath];
    cell.actionDelegate = self;
    
    DownloadTask * obj = [[DownloadManager sharedDownload].tasks objectAtIndex:indexPath.row];
    cell.titleLabel.text = obj.targetName;
    
    if (obj.info.totalBytesExpectedToWrite != 0) {
        NSString * written = [NSByteCountFormatter stringFromByteCount:obj.info.totalBytesWritten countStyle:NSByteCountFormatterCountStyleFile];
        NSString * total = [NSByteCountFormatter stringFromByteCount:obj.info.totalBytesExpectedToWrite countStyle:NSByteCountFormatterCountStyleFile];
        cell.sizeLabel.text = [NSString stringWithFormat:@"%@/%@", written, total];
        
        cell.progressView.progress = obj.info.totalBytesWritten * 1.0 / obj.info.totalBytesExpectedToWrite;
    } else {
        cell.sizeLabel.text = nil;
        cell.progressView.progress = 0.f;
    }
    
    cell.speedLabel.text = nil;
    
    switch (obj.status) {
        case DownloadTaskStatusError: {
            cell.statusLabel.text = @"下载失败";
        }
            break;
        case DownloadTaskStatusUnknown: {
            cell.statusLabel.text = nil;
        }
            break;
        case DownloadTaskStatusWaiting: {
            cell.statusLabel.text = @"正在连接...";
        }
            break;
        case DownloadTaskStatusDownloading:
        case DownloadTaskStatusMoving: {
            cell.statusLabel.text = @"下载中...";
            
            cell.speedLabel.text = [[NSByteCountFormatter stringFromByteCount:obj.speed.speedBytes countStyle:NSByteCountFormatterCountStyleFile] stringByAppendingString:@"/s"];
        }
            break;
        case DownloadTaskStatusFinish: {
            cell.statusLabel.text = @"下载完成";
        }
            break;
        case DownloadTaskStatusPause: {
            cell.statusLabel.text = @"已暂停";
        }
            break;
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    DownloadTask * obj = [[DownloadManager sharedDownload].tasks objectAtIndex:indexPath.row];
    
    if (obj.status == DownloadTaskStatusPause) {
        [[DownloadManager sharedDownload] resume:obj];
    } else {
        [[DownloadManager sharedDownload] pause:obj];
    }
}

- (NSArray<NSString *> *)urlStrings {
    if (!_urlStrings) {
        _urlStrings = @[
            @"http://file.zaichengzhang.net/ChildPlat/Anniversary/20211202/Video/2356f1fc-889a-4211-97bd-68f09bf8074e.mp4",
            @"http://file.zaichengzhang.net/ChildPlat/Anniversary/20211201/Video/dab4e438-c667-4b9a-a371-2703c816493e.mp4",
            @"http://file.zaichengzhang.net/ChildPlat/Anniversary/20211201/Photo/94a21369-4398-44e4-92ad-6c3d012556e8.jpg",
            @"http://file.zaichengzhang.net/ChildPlat/Anniversary/20211103/Photo/754C5812-097D-44D7-82B1-34A74EE4189A.jpg",
        ];
    }
    return _urlStrings;
}

@end
